from django.shortcuts import render

# Create your views here.
from rest_framework.generics import CreateAPIView, RetrieveAPIView, GenericAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
# from .models import User
from users.models import User
from users.serializers import RegisterCreateUserSerializer, UserDetailSerializer, EmailUpdateSerializer


class RegisterUserNameView(APIView):

    def get(self, request, username):

        # 1.判断username是否存在
        count = User.objects.filter(username=username).count()

        # 2.构建上下文
        context = {
            'count': count,
            'username': username
        }

        # 3.返回响应
        return Response(context)


class RegisterCreateUserView(CreateAPIView):

    serializer_class = RegisterCreateUserSerializer


class UserDetailView(GenericAPIView):

    permission_classes = [IsAuthenticated]

    serializer_class = UserDetailSerializer

    def get(self, request):

        user = request.user

        serializer = self.get_serializer(instance=user)

        return Response(serializer.data)


class UserDetailView2(RetrieveAPIView):

    permission_classes = [IsAuthenticated]

    sirializer_class = UserDetailSerializer

    # 重写方法，返回用户模型对象
    def get_object(self):

        return self.request.user


class EmailUpdateView(UpdateAPIView):

    permission_classes = [IsAuthenticated]

    serializer_class = EmailUpdateSerializer

    def get_object(self):

        return self.request.user


class VerifyEmailView(APIView):

    def get(self, request):

        token = request.query_params.get('token')
        if token is None:
            return Response(status=400)

        user = User.user_by_token(token)[0]
        if user is None:
            return Response(status=400)

        else:
            user.email_active = True
            user.save()

        return Response({'message': 'ok'})
